
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Template," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>工具类的助手 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        工具类的助手
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Template/" rel="tag">Ember-Template</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 5 分钟</span>
    </header>

    <div class="post-content">
      <p>本篇主要介绍格式转换、自定义<code>helper</code>、自定义<code>helper</code>参数、状态<code>helper</code>、HTML标签转义这几个方面的东西。</p>
<p>按照文章惯例先准备好测试所需要的数据、文件。仍然是使用<a target="_blank" rel="noopener" href="http://ember-cli.com/user-guide">Ember CLI</a>命令，这次我们创建的是<code>helper</code>、<code>controller</code>、<code>route</code>（创建<code>route</code>会自动创建<code>template</code>）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ember generate helper my-helper</span><br><span class="line">ember generate controller tools-helper</span><br><span class="line">ember generate route tools-helper</span><br></pre></td></tr></table></figure>

<h3 id="1，自定义helper"><a href="#1，自定义helper" class="headerlink" title="1，自定义helper"></a>1，自定义<code>helper</code></h3><p>自定义助手非常简答直接使用<a target="_blank" rel="noopener" href="http://ember-cli.com/user-guide">Ember CLI</a>命令生成就可以了。当然你也可以手动创建，自定义的助手都是放在<code>app/helpers</code>目录下。Ember会根据模板上使用的助手自动到这个目录查找。定义了<code>helper</code>之后你就可以直接在模板上使用。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  //app/templates/tools-helper.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line">my-helper: &#123;&#123;my-helper&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>程序没有报错，但是什么也没有显示。是的什么也没有显示。没有显示就对了。因为我们对于刚刚创建的<code>app/helpers/my-helper.js</code>没有做任何的修改。你可以看这个文件的代码。直接返回了<code>params</code>，目前来说这个参数是空的。修改这个文件，直接返回一个字符串。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/helpers/my-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">myHelper</span>(<span class="params">params<span class="regexp">/*, hash*/</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="string">&quot;hello world!&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(myHelper);</span><br></pre></td></tr></table></figure>
<p>此时可以在页面上看到直接打印了“hello world!”这个字符串。这就是一个最简单的自定义<code>helper</code>，不过这么简单<code>helper</code>显然是没啥用的。Ember的作者肯定不会这么傻的，接着下面介绍<code>helper</code>的参数。<br>注意：使用模板的名字跟文件名是一致的。不同单词使用<code>-</code>分隔，虽然这个命名规则不是强制性的但是Ember建议你这么做，Ember会自动根据<code>helper</code>的名字找到对应的自定义的<code>helper</code>，然后执行<code>helper</code>里名字为<code>myHelper</code>（名字是文件名的驼峰式命名）的方法，在这个方法里你可以实现你需要的逻辑。这些工作Ember自动帮你做了，不需要你编写解析的代码。</p>
<h4 id="1，helper无名参数"><a href="#1，helper无名参数" class="headerlink" title="1，helper无名参数"></a>1，<code>helper</code>无名参数</h4><p>上面的代码定义了一个最简单的helper，不过没啥用，Ember允许在自定义的helper上添加自定义的参数。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">my-helper-param: &#123;&#123;my-helper &#x27;chen&#x27; &#x27;ubuntuvim&#x27;&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>在这个自定义的<code>helper</code>中增加了两个参数，既然有了参数那么又有什么用呢？当然是有用的，你可以在自定义的<code>helper</code>中获取参数，获取模板的参数有两种方式。<br><br><strong>写法一</strong><br></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/helpers/my-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">myHelper</span>(<span class="params">params<span class="regexp">/*, hash*/</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 获取模板上的参数</span></span><br><span class="line">    <span class="keyword">var</span> p1 = params[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">var</span> p2 = params[<span class="number">1</span>];</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;p1 = &#x27;</span> + p1 + <span class="string">&quot;, p2 = &quot;</span> + p2);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> p1 + <span class="string">&quot; &quot;</span> + p2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(myHelper);</span><br></pre></td></tr></table></figure>
<p><br><strong>写法二</strong><br></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/helpers/my-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">myHelper</span>(<span class="params">[arg1, arg2]</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;p1 = &#x27;</span> + arg1 + <span class="string">&quot;, p2 = &quot;</span> + arg2);</span><br><span class="line">    <span class="keyword">return</span> arg1 + <span class="string">&quot; &quot;</span> + arg2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(myHelper);</span><br></pre></td></tr></table></figure>
<p>参数很多的情况使用第一种方式用循环获取参数比较方便，参数少情况第二种方式更加简便，直接使用！</p>
<p><strong>注意：参数的顺序与模板传入的顺序一致。</strong></p>
<p>页面刷新之后可以在页面或者浏览器控制台看到在<code>helper</code>上设置的参数值了吧！！如果你的程序没有错误在浏览器上你也会得到下图的结果：</p>
<p><img src="/content/images/2016/03/52.png" alt="result"></p>
<p>第一行因为在模板上没有传入参数所以是<code>undefined</code>，第二行传入了参数，并且直接从<code>helper</code>返回显示。</p>
<h4 id="2，helper命名参数"><a href="#2，helper命名参数" class="headerlink" title="2，helper命名参数"></a>2，<code>helper</code>命名参数</h4><p>上一点演示了在模板中传递无名的参数，这一小节讲为你介绍有名字的参数。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">my-helper-named-param: &#123;&#123;my-helper firstName=&#x27;chen&#x27; lastName=&#x27;ubuntuvim&#x27;&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>相比于第一种使用方式给每个参数增加了参数名。那么<code>helper</code>处理类有要怎么去获取这些参数呢？</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/helpers/my-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对于命名参数使用namedArgs获取</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">myHelper</span>(<span class="params">params, namedArgs</span>) </span>&#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;namedArgs = &#x27;</span> + namedArgs);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;params = &#x27;</span> + params);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;=========================&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span> namedArgs.firstName + <span class="string">&quot;, &quot;</span> + namedArgs.lastName; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(myHelper);</span><br></pre></td></tr></table></figure>
<p>获取命名参数使用<code>namedArgs</code>，其实你也可以按照前面的方法使用<code>params</code>获取参数值。你在第一行打印语句上打上断点，是浏览器进入debug模式，但不执行，你会发现<code>params</code>一开始是有值<code>namedArgs</code>没有值，但是执行到最后正好相反，<code>params</code>的值被置空了，<code>namedArgs</code>却有了模板设置的值，你可以猜想下，Ember可能是把<code>params</code>的值赋值到<code>namedArgs</code>上了，不同之处是<code>namedArgs</code>是以对象属性的方式取值并且不用关心参数的顺序问题，<code>params</code>是以数组的方式取值需要关心参数的顺序。</p>
<p><img src="/content/images/2016/03/49.png" alt="result"></p>
<h3 id="2，时间格式化"><a href="#2，时间格式化" class="headerlink" title="2，时间格式化"></a>2，时间格式化</h3><p>做开发的都应该遇到过数字或者时间格式问题，特别是时间格式问题应该是最普遍遇到的。不同的项目时间格式往往不同，有<code>yyyy-DD-mm</code>类型的有<code>yyyyMMdd</code>类型以及其他类型。</p>
<p>同样的Ember模板也给我们提供了类似的解决办法，那就是自定义格式化方法。通过自定义<code>helper</code>实现数据的格式化。</p>
<ol>
<li>创建格式化<code>helper</code>：<code>ember generate helper format-date</code></li>
<li>在<code>controller</code>初始化一个时间数据。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/controllers/tools-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    currentDate: <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>默认情况下显示数据<code>currentDate</code>。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  //app/templates/tools-helper.hbs  --&gt;</span></span><br><span class="line">&#123;&#123; currentDate&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>此时显示的默认的数据格式。<br>运行<a target="_blank" rel="noopener" href="http://localhost:4200/tools-helper">http://localhost:4200/tools-helper</a>，可以在页面看到：<code>Mon Sep 21 2015 23:46:03 GMT+0800 (CST) </code>这种格式的时间。显然不太合法我们的习惯，看着都觉得不舒服。那下面使用自定义的<code>helper</code>格式化日期格式。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/helpers/format-data.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 注意：方法名字是文件名去掉中划线变大写，驼峰式写法</span></span><br><span class="line"><span class="comment"> * 或者你也可以直接作为helper的内部函数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param  <span class="type">&#123;[type]&#125;</span> </span>params 从助手&#123;&#123;format-data&#125;&#125;传递过来的参数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">formatDate</span>(<span class="params">params<span class="regexp">/*, hash*/</span></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;params = &#x27;</span> + params);</span><br><span class="line">    <span class="keyword">var</span> d = <span class="built_in">Date</span>.parse(params);</span><br><span class="line">    <span class="keyword">var</span> dd = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="built_in">parseInt</span>(d)).toLocaleString().replace(<span class="regexp">/:\d&#123;1,2&#125;$/</span>,<span class="string">&#x27; &#x27;</span>);  <span class="comment">//  2015/9/21 下午11:21</span></span><br><span class="line">    <span class="keyword">var</span> v = dd.replace(<span class="string">&quot;/&quot;</span>, <span class="string">&quot;-&quot;</span>).replace(<span class="string">&quot;/&quot;</span>, <span class="string">&quot;-&quot;</span>).substr(<span class="number">0</span>, <span class="number">9</span>);</span><br><span class="line">    <span class="keyword">return</span> v;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(formatDate);</span><br></pre></td></tr></table></figure>
<p>或者你也可以这样写。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(<span class="function"><span class="keyword">function</span> <span class="title">formatDate</span>(<span class="params">params<span class="regexp">/*, hash*/</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> d = <span class="built_in">Date</span>.parse(params);</span><br><span class="line">    <span class="keyword">var</span> dd = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="built_in">parseInt</span>(d)).toLocaleString().replace(<span class="regexp">/:\d&#123;1,2&#125;$/</span>,<span class="string">&#x27; &#x27;</span>);  <span class="comment">//  2015/9/21 下午11:21</span></span><br><span class="line">    <span class="keyword">var</span> v = dd.replace(<span class="string">&quot;/&quot;</span>, <span class="string">&quot;-&quot;</span>).replace(<span class="string">&quot;/&quot;</span>, <span class="string">&quot;-&quot;</span>).substr(<span class="number">0</span>, <span class="number">9</span>);</span><br><span class="line">    <span class="keyword">return</span> v;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>为了简便，直接就替换字符，修改时间分隔字 <code>/</code>为<code>-</code>。   然后修改显示的模板，使用自定义的<code>helper</code>。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  //app/templates/tools-helper.hbs  --&gt;</span></span><br><span class="line">&#123;&#123;format-date currentDate&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>此时页面上显示的时间是我们熟悉的时间格式：</p>
<p><img src="/content/images/2016/03/50.png" alt="result"></p>
<p>上面介绍的是简答的用法，Ember还允许你传入时间的格式（<code>format</code>），以及本地化类型（<code>locale</code>）。</p>
<ol>
<li>用命令新建一个<code>helper</code>：<code>ember generate helper format-date-time</code></li>
<li>在<code>controller</code>类里新增两个用于测试的属性<code>cDate</code>和<br><code>currentTime</code>。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/controllers/tools-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    currentDate: <span class="keyword">new</span> <span class="built_in">Date</span>(),</span><br><span class="line">    cDate: <span class="string">&#x27;2015-09-22&#x27;</span>,</span><br><span class="line">    currentTime: <span class="string">&#x27;00:22:32&#x27;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  //app/templates/tools-helper.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">format-date-time: &#123;&#123;format-date-time currentDate cDate currentTime format=&quot;yyyy-MM-dd h:mm:ss&quot;&#125;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">format-date-time-local: &#123;&#123;format-date-time currentDate cDate currentTime format=&quot;yyyy-MM-dd h:mm:ss&quot; locale=&quot;en&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>在助手<code>format-date-time</code>上一共有4个属性。<code>cDate</code>和<code>currentTime</code>是从上下文获取值的变量，<code>format</code>和<code>locale</code>是Ember专门提供用于时间格式化的属性。</p>
<p>下面看看<code>format-date-time</code>这个助手怎么获取页面的数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/helpers/format-date-time.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">formatDateTime</span>(<span class="params">params, hash</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  参数的顺序跟模板&#123;&#123;format-date-time currentDate cDate currentTime&#125;&#125;上使用顺序一致，</span></span><br><span class="line">    <span class="comment">//  cDate比currentTime先，所以第一个参数是cDate</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;params[0] = &#x27;</span> + params[<span class="number">0</span>]);  <span class="comment">//第一个参数是cDate,</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;params[1] = &#x27;</span> + params[<span class="number">1</span>]);  <span class="comment">//  第二个是currentTime</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;hash.format = &#x27;</span> + hash.format);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;hash.locale = &#x27;</span> + hash.locale);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;------------------------------------&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> params;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(formatDateTime);</span><br></pre></td></tr></table></figure>
<p>我只是演示怎么获取页面<code>format-date-time</code>助手设置的值，得到页面设置的值你想干嘛就干嘛⋯⋯<br>最后看看浏览器控制台的输出信息。</p>
<p><img src="/content/images/2016/03/51.png" alt="result"></p>
<p>因为页面使用了两次这个助手，所以自然也就打印了两次。</p>
<h4 id="3，转义HTML标签"><a href="#3，转义HTML标签" class="headerlink" title="3，转义HTML标签"></a>3，转义HTML标签</h4><p>官方的解释是：为了保护你的应用免受跨点脚本攻击（XSS），Ember会自动把<code>helper</code>返回值中的HTML标签转义。</p>
<p>新建一个<code>helper</code>：<code>ember generate helper escape-helper</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/helpers/escape-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">escapeHelper</span>(<span class="params">params<span class="regexp">/*, hash*/</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// return Ember.String.htmlSafe(`&lt;b&gt;$&#123;params&#125;&lt;/b&gt;`);</span></span><br><span class="line">  <span class="keyword">return</span> <span class="string">`&lt;b&gt;<span class="subst">$&#123;params&#125;</span>&lt;/b&gt;`</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Helper.helper(escapeHelper);</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">escape-helper: &#123;&#123;escape-helper &quot;helloworld!&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>此时页面上会直接显示“<b>helloworld!</b>”而不是“helloworld”被加粗了！如果你确定你返回的字符串是安全的你可用使用<code>htmlSafe</code>方法，这个方法不会把HTML代码转义，HTML代码仍然能起作用，那么页面显示的将是加粗的“helloworld！”。</p>
<p>到此模板这一章全部讲完了！！！但愿你能从中得到一点收获！！后面的文章将开始讲<code>route</code>，<code>route</code>在<a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/03/22/ember-js-ru-men-zhi-nan-zhi-shi-san-link-to/">Ember.js 入门指南之十三NaN 助手</a>这一篇已经讲过一点，但不是很详细。接下来的一章将会为你详细解释<code>route</code>。<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/templetes/%E7%95%AA%E5%A4%96%E7%AF%87%EF%BC%8C%E8%B7%AF%E7%94%B1%E3%80%81%E6%A8%A1%E6%9D%BF%E7%9A%84%E6%89%A7%E8%A1%8C%E3%80%81%E6%B8%B2%E6%9F%93%E9%A1%BA%E5%BA%8F/" rel="next" title="番外篇，路由、模板的执行、渲染顺序">
          番外篇，路由、模板的执行、渲染顺序
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/templetes/%E5%86%85%E7%BD%AEHelper/" rel="prev" title="内置Helper">
            内置Helper
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%8C%E8%87%AA%E5%AE%9A%E4%B9%89helper"><span class="toc-text">1，自定义helper</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%8Chelper%E6%97%A0%E5%90%8D%E5%8F%82%E6%95%B0"><span class="toc-text">1，helper无名参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%8Chelper%E5%91%BD%E5%90%8D%E5%8F%82%E6%95%B0"><span class="toc-text">2，helper命名参数</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%8C%E6%97%B6%E9%97%B4%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-text">2，时间格式化</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%8C%E8%BD%AC%E4%B9%89HTML%E6%A0%87%E7%AD%BE"><span class="toc-text">3，转义HTML标签</span></a></li></ol></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '工具类的助手', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
